<?php
/**
 * Created by PhpStorm.
 * User: whimp
 * Date: 2017/2/23
 * Time: 12:01
 */
class Service_Public{
    /**
     * 注册
     * @param $data
     */

    public static function register($data){
//        var_dump($data);exit();
        if(!$data['username']){
            $ret = array('result' => 'error', 'errNo' => 1, 'msg' => '用户名不能为空!');
            return $ret;
        }
        if(!$data['password']){
            $ret = array('result' => 'error', 'errNo' => 2, 'msg' => '密码不能为空!');
            return $ret;
        }
//        if(!$data['account_uid']){
//            $ret = array('result' => 'error', 'errNo' => 3, 'msg' => '缘分吧ID不能为空!');
//            return $ret;
//        }
        if(strlen($data['mobile'])!=11){
            $ret = array('result' => 'error', 'errNo' => 4, 'msg' => '电话错误！');
            return $ret;

        }

        $usertable=new FTable('user');
        $result=$usertable->where(array('mobile'=>$data['mobile']))->find();
        if($result){
            $ret = array('result' => 'error', 'errNo' => 5, 'msg' => '电话号码重复！');
            return $ret;
        }
//        /**
//         * 上级ID检测
//         */
//        if($data['proxy_id']){
//            $managertable=new FTable('user');
//            $manager=$managertable->where(array('uid'=>$data['proxy_id'],'account_type'=>2))->find();
//            if(!$manager){
//                $ret = array('result' => 'error', 'errNo' => 6, 'msg' => '推荐ID错误!');
//                return $ret;
//            }
//        }
//        $data['mid']=$manager['mid'];
//        /**
//         * 缘分吧ID验证
//         */
//        $flag = Service_Yfb::checkuser($data['account_uid']);
//        if(!$flag){
//            $ret = array('result' => 'error', 'errNo' => 7, 'msg' => '缘分吧账号无效!');
//            return $ret;
//        }

        $data['mobile']=$data['mobile']?$data['mobile']:"";
        $data['avatar']=$data['avatar']?$data['avatar']:"";
        $data['proxy_id']=$data['proxy_id']?$data['proxy_id']:0;
        $data['account_uid']=$data['account_uid']?$data['account_uid']:0;
        $data['reg_time'] = CURRENT_DATE_TIME;
        $usertable=new FTable('user');
        $result=$usertable->insert($data);
        if($result){
//            /**
//             * 通知缘分吧绑定用户组
//             */
//            if($data['proxy_id']){
//                Service_Yfb::setbeauty($data['account_uid'],$data['proxy_id']);
//            }
            /**
             * 注册数统计
             */
            $regtable=new FTable('reg_report');
            $reg=$regtable->where(array('mid'=>$data['proxy_id']))->find();
            if($reg){
                if(date('d',strtotime($reg['update_time']))==date('d',time())){
                    $sql="update reg_report set dayreg=dayreg+1,monthreg=monthreg+1,totolreg=totolreg+1 where mid={$data['proxy_id']}";
                    FDB::query($sql);
                }else{
                    if(date('m',strtotime($reg['update_time']))==date('m',time())){
                        $sql="update reg_report set dayreg=1,monthreg=monthreg+1,totolreg=totolreg+1 where mid={$data['proxy_id']}";
                        FDB::query($sql);
                    }else{
                        $sql="update reg_report set dayreg=1,monthreg=1,totolreg=totolreg+1 where mid={$data['proxy_id']}";
                        FDB::query($sql);
                    }
                }
            }else{
                $regtable->insert(array('mid'=>$data['proxy_id'],'dayreg'=>1,'monthreg'=>1,'totolreg'=>1));
            }
            //更新体验师数量统计
            Service_Manager::setExperTotal($data['proxy_id']);
            /**
             * 自动设置系统模板
             */
            Service_Experience::setRegisterRandTpl($result);
            //设置cookie
            $auth_str = md5("{$data['username']}|{$data['password']}");
            FCookie::set('auth', "{$result}\t{$auth_str}", FConfig::get('global.session_time'));
            $ret = array('result' => 'success', 'msg' => '注册成功');
            return $ret;
        }else{
            $ret = array('result' => 'error', 'errNo' => 5, 'msg' => '注册失败');
            return $ret;

        }

    }

    /**
     * 登录
     * @param $uid
     * @param $password
     * @return array|bool
     */
    public static function login($uid,$password){
        if($uid&&$password){

            $usertable=new FTable('user');
            $where="username='{$uid}' or uid='{$uid}' or mobile='{$uid}'";
            $user=$usertable->where($where)->find();
            if(!$user){
                $data = array('result' => 'error','user'=>$user, 'msg' => '用户不存在');
                return $data;
//                FResponse::output(array('result' => 'error','user'=>$user, 'msg' => '用户不存在'));
            }
            if($user['password']==md5($password) && $user['status'] < 9){
                $auth_str = md5("{$user['username']}|{$user['password']}");
                FCookie::set('auth', "{$user['uid']}\t{$auth_str}", FConfig::get('global.session_time'));
                $data = array('result' => 'success','user'=>$user, 'msg' => '登录成功');
                return $data;
//                FResponse::output(array('result' => 'success','user'=>$user, 'msg' => '登录成功'));
            }else{
                $data = array('result' => 'error','user'=>$user, 'msg' => '登录失败');
                return $data;
//                FResponse::output(array('result' => 'error','user'=>$user, 'msg' => '登录失败'));
//                return false;
            }
        }
    }

    /**
     * 资料提交
     * @param $uid
     * @param $data
     * @return bool
     */
    public static function modify($uid,$data){
        if(!$uid){
            $data = array('result' => 'error', 'errNo' => 2, 'msg' => 'UID不能为空！');
            return $data;
//            FResponse::output(array('result' => 'error', 'errNo' => 2, 'msg' => 'UID不能为空！'));
        }
        $usertable=new FTable('user');
        $result=$usertable->where(array('uid'=>$uid))->find();
        if($result['modify']==2){
            $data = array('result' => 'error', 'errNo' => 2, 'msg' => '修改资料请联系管理员！');
            return $data;
//            FResponse::output(array('result' => 'error', 'errNo' => 2, 'msg' => '修改资料请联系管理员！'));
        }
        if($data['mobile']){
            if(strlen($data['mobile'])!=11){
                $data = array('result' => 'error', 'errNo' => 3, 'msg' => '电话错误！');
                return $data;
//                FResponse::output(array('result' => 'error', 'errNo' => 3, 'msg' => '电话错误！'));
            }
            $usertable=new FTable('user');
            $result=$usertable->where(array('mobile'=>$data['mobile']))->find();
            if($result && $result['uid'] != $uid){
                $data = array('result' => 'error', 'errNo' => 4, 'msg' => '电话号码重复！');
                return $data;
//                FResponse::output(array('result' => 'error', 'errNo' => 4, 'msg' => '电话号码重复！'));
            }
            $ret2=$usertable->where(array('username'=>$data['username']))->find();
            if($ret2  && $ret2['uid'] != $uid){
                $data = array('result' => 'error', 'errNo' => 5, 'msg' => '用户名重复！');
                return $data;
//                FResponse::output(array('result' => 'error', 'errNo' => 5, 'msg' => '用户名重复！'));
            }

        }
         //银行卡号位数校验
        if($data['bank_account']){
            if (strlen($data['bank_account']) > 19 || strlen($data['bank_account']) < 16) {
                $data = array('status' => 'error', 'errNo' => 4, 'msg' => '银行卡号不正确！');
                return $data;
            }
        }
        /**
         * 通知缘分吧绑定用户组
         */
        if($data['proxy_id']){
            Service_Yfb::setbeauty($data['account_uid'],$data['proxy_id']);
        }
        //置修改标志位
        $data['modify']==2;
        $usertable=new FTable('user');
        $result=$usertable->update($data,array('uid'=>$uid));
        if($result){
            $data = array('result' => 'success', 'msg' => '更新资料成功');
            return $data;
//            FResponse::output(array('result' => 'success', 'msg' => '更新资料成功'));
        }else{
            $data = array('result' => 'error', 'errNo' => 5, 'msg' => '更新资料失败');
            return $data;
//            FResponse::output(array('result' => 'error', 'errNo' => 5, 'msg' => '更新资料失败'));
        }
    }

    /**
     * 获取用户资料
     * @param $uid
     * @return array|bool
     */
    public static function getUserDetail($uid){
        if($uid){
            $cache_key_user = 'user_' . $uid;
            $userdata = FCache::get($cache_key_user);
            $userdata=json_decode($userdata,true);
            if(!$userdata){
                $usertable=new FTable('user');
                $where="uid='{$uid}'";
                $userdata=$usertable->where($where)->find();
                FCache::set($cache_key_user, json_encode($userdata), 10 * 24 * 3600);
            }
            if($userdata){
//                FResponse::output(array('result' => 'success','user'=>$userdata, 'msg' => '获取成功'));
                return $userdata;
            }else{
                return false;
            }
        }
    }

    public static function clearUserDetailCache($uid){
        $cache_key = 'user_'.$uid;
        if($uid){
            FCache::delete($cache_key);
            self::getUserDetail($uid);
        }
    }

    public static function authCode()
    {
        session_start();
        /**
         * 生成验证码图片
         */
        header("Content-type: image/PNG ");
        srand((double)microtime() * 1000000);
        $authnum = rand(1000, 9999);
        $_SESSION['rand_code'] = $authnum;
        $im = imagecreate(62, 20);
        imagecolorallocate($im, 0, 0, 0);
        $white = imagecolorallocate($im, 255, 255, 255);
        /**
         * 将五位整数验证码绘入图片
         */
        imagestring($im, 5, 10, 3, $authnum, $white);
        /**
         * 加入干扰象素
         */
        for ($i = 0; $i < 200; $i++) {
            $randcolor = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
            imagesetpixel($im, rand() % 70, rand() % 30, $randcolor);
        }
        imagepng($im);
        imagedestroy($im);
    }

    /**
     * 本周排行
     */
    public static function toplist(){

        $cacheweekKey = "cache_weeklist";
//        FCache::delete($cacheweekKey);
        $backlist = FCache::get($cacheweekKey);
        $backlist = json_decode($backlist, true);
        if(!$backlist){
            $start_time = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 6, date("Y")));
            $end_time = date("Y-m-d", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y")));
            $sql="select dr.uid,username,sum(paymoney) AS money  from date_report dr left JOIN user u on u.uid=dr.uid where dr.report_date>'{$start_time}' group by uid order by sum(paymoney) desc limit 20";
            $backlist = FDB::fetch($sql);
            FCache::set($cacheweekKey, json_encode($backlist), 60 * 5);
        }
        return $backlist;
   }
    /**
     * 本月排行
     */
    public static function monthtoplist(){

        $cachemonthKey = "cache_monthlist";
//        FCache::delete($cacheweekKey);
        $backlist = FCache::get($cachemonthKey);
        $backlist = json_decode($backlist, true);
        if(!$backlist){
            $time=date("Y-m-d",mktime(0, 0 , 0,date("m")-1,date('d'),date("Y")));
            $sql="select dr.uid,username,sum(paymoney) AS money  from date_report dr left JOIN user u on u.uid=dr.uid where dr.report_date>'{$time}' group by uid order by sum(paymoney) desc limit 20";
            $backlist = FDB::fetch($sql);
            FCache::set($cachemonthKey, json_encode($backlist), 60 * 60);
        }
        return $backlist;
    }
    /**
     * 热门排行
     */
    public static function hotlist(){

        $cachemonthKey = "cache_monthlist_hot";
//        FCache::delete($cacheweekKey);
        $backlist = FCache::get($cachemonthKey);
        $backlist = json_decode($backlist, true);
        if(!$backlist){
            $time=date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m")-1,date('d'),date("Y")));
            $sql="select dr.uid,username,avatar,sum(paymoney) AS money  from date_report dr left JOIN user u on u.uid=dr.uid where dr.report_date>'{$time}' group by uid order by sum(paymoney) desc limit 20";
            $backlist = FDB::fetch($sql);
            FCache::set($cachemonthKey, json_encode($backlist), 60 * 60);
        }
        return $backlist;
    }
    /**
     * 体验师人数
     */
    public static function tiyannum(){

//        $cacheKey = "cache_tiyannum";
//        $backlist = FCache::get($cacheKey);
//        if(!$backlist){
//            $time=date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
            $sql="select count(uid) num from user where account_type=1";
            $backlist = FDB::fetchFirst($sql);
//            FCache::set($cacheKey, $backlist['num'], 60 * 5);
//        }
        return $backlist['num'];
    }

    /**
     * 体验师代理结算明细
     * @param $starttime 开始日期 如2017-03-02
     * @param $endtime
     * @return mixed
     */
    public static function settlement($starttime,$endtime,$page=1,$limit=20){
        global $_F;
        $where['uid']=$_F['uid'];
        if($starttime){
            $where['settlementtime']['gte'] = $starttime . ' 00:00:00';
        }
        if($starttime){
            $where['settlementtime']['lte'] = $endtime . ' 23:59:59';
        }
        $settlementTable = new FTable('settlement','');
        $settlementlist = $settlementTable
            ->where($where)
            ->order(array('auto_id'=>'desc'))
            ->page($page)->limit($limit)
            ->select();

        $sum = $settlementTable
            ->fields('sum(realincome) as realincome_sum')
            ->where($where)
            ->find();

        $pagerInfo = $settlementTable->getPagerInfo();
        $list['list']=$settlementlist;
        $list['page_info']=$pagerInfo;
        $list['realincome_sum']=$sum['realincome_sum'];
        return $list;
    }

    /**
     * 获取用户收入
     * @param $uid
     */
    public static function getincome($uid){
        $incomeTable = new FTable('date_report');
        $todayIncome = $incomeTable->fields('paymoney')->where(array('report_date' => date('Y-m-d'), 'uid' => $uid))->find();
        $nosettlementIncome = $incomeTable->fields('sum(paymoney) as money_total')->where(array('paystatus' => 1, 'uid' => $uid))->find();
        $totalIncome = $incomeTable->fields('sum(paymoney) as money_total')->where(array('uid' => $uid))->find();
        $result=array(
            'todayIncome'=>$todayIncome['paymoney']?$todayIncome['paymoney']:0,
            'nosettlementIncome'=>$nosettlementIncome['money_total']?$nosettlementIncome['money_total']:0,
            'totalIncome'=>$totalIncome['money_total']?$totalIncome['money_total']:0,
        );
        return $result;
    }

    public static function checkMobile($mobile)
    {
        if (preg_match("/^1[345678]{1}\d{9}$/", $mobile)) {
            return true;
        } else {
            return false;
        }
    }

    public static function getChannelName($url){
        $url_arr = explode('#', $url);
        $table = new FTable('channel');
        $domain = strtolower($url_arr[0]);
        $where = array('domain' => $domain);
        $result = $table->where($where)->find();
        if($result){
            return $result['channel_name'];
        }else{
            return '';
        }
    }

}